import ctypes
import os
import platform
import psutil
import sys
import time
from ctypes import wintypes

class AntiDebug:
    """反调试保护"""
    
    @staticmethod
    def is_debugger_present():
        """检测调试器"""
        if platform.system() == "Windows":
            kernel32 = ctypes.windll.kernel32
            return kernel32.IsDebuggerPresent()
        return False
    
    @staticmethod
    def check_blacklisted_processes():
        """检查黑名单进程"""
        blacklist = [
            'ollydbg.exe', 'ida.exe', 'ida64.exe', 'idag.exe', 'idag64.exe',
            'idaw.exe', 'idaw64.exe', 'idaq.exe', 'idaq64.exe', 'idau.exe',
            'idau64.exe', 'scylla.exe', 'scylla_x64.exe', 'scylla_x86.exe',
            'protection_id.exe', 'x64dbg.exe', 'x32dbg.exe', 'windbg.exe',
            'reshacker.exe', 'ImportREC.exe', 'IMMUNITYDEBUGGER.EXE',
            'MegaDumper.exe', 'CodeBrowser.exe', 'ResourceHacker.exe',
            'x96dbg.exe', 'x32_dbg.exe', 'x64_dbg.exe', 'Cheat Engine.exe',
            'Debug.exe', 'debugger.exe'
        ]
        
        for proc in psutil.process_iter(['name']):
            try:
                if proc.info['name'].lower() in [p.lower() for p in blacklist]:
                    return True
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue
        return False
    
    @staticmethod
    def check_vm_environment():
        """检测虚拟机环境"""
        vm_indicators = [
            'VMware', 'VirtualBox', 'VBOX', 'QEMU', 'Xen', 'Hyper-V',
            'Virtual', 'vmware', 'vbox', 'qemu'
        ]
        
        # 检查系统信息
        system_info = platform.platform().lower()
        for indicator in vm_indicators:
            if indicator.lower() in system_info:
                return True
        
        # 检查MAC地址
        try:
            import uuid
            mac = ':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff) 
                           for elements in range(0,2*6,2)][::-1])
            vm_macs = ['00:0c:29', '00:1c:14', '00:50:56', '08:00:27']
            for vm_mac in vm_macs:
                if mac.startswith(vm_mac):
                    return True
        except:
            pass
        
        return False
    
    @staticmethod
    def anti_debug_check():
        """综合反调试检查"""
        if AntiDebug.is_debugger_present():
            return False, "检测到调试器"
        
        if AntiDebug.check_blacklisted_processes():
            return False, "检测到逆向工程工具"
        
        if AntiDebug.check_vm_environment():
            return False, "检测到虚拟机环境"
        
        return True, "环境检查通过"

class CodeObfuscator:
    """代码混淆器"""
    
    @staticmethod
    def obfuscate_string(s):
        """字符串混淆"""
        return ''.join([chr(ord(c) ^ 0x5A) for c in s])
    
    @staticmethod
    def deobfuscate_string(s):
        """字符串反混淆"""
        return ''.join([chr(ord(c) ^ 0x5A) for c in s])

def protection_check():
    """保护检查入口"""
    success, message = AntiDebug.anti_debug_check()
    if not success:
        # 检测到威胁，退出程序
        print(f"安全检查失败: {message}")
        sys.exit(1)
    return True